package zb;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author wzby
 * @Date: 2022/8/2 8:40
 */
public class FileCountRows {
    //读取文件行数
    public static void main(String[] args) {
        String f = "E:\\idea\\java\\ch01\\src\\A.java";
        try (var s = new FileInputStream(f)){
            String src = new String(s.readAllBytes());
            //方法一
            System.out.println(src.lines().count());
            //方法二 使用pattern类
            Pattern p = Pattern.compile("\n");
            Matcher m = p.matcher(src);
            int count = 0;
            while (m.find()){
                ++count;
            }
            System.out.println(count);
        }catch (Exception e){

        }
        //Buff bis ;
        //方法三：读取一个java源码文件，分别添加行号，并保存输出到另一个文件中
        try (var buf = new BufferedReader(new FileReader(f));
        FileOutputStream fos = new FileOutputStream("E:\\idea\\java\\ch09\\src\\f\\mysrc.txt");
        ){
            int c = 0;
            String line = null;
            while ((line = buf.readLine()) != null){
                String lin = String.format("%d,%s %n",++c,line);
                fos.write(lin.getBytes());
            }
        }catch (Exception e){

        }
    }
}
